package com.java.web.excel;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.java.web.util.ExcelUtils;

public class ExcelImportServlet extends HttpServlet {


	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse resp)
			throws ServletException, IOException {
		String excel=request.getParameter("excel");
		System.out.println(excel);
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("utf-8");//支持中文文件名
		try{
			List<FileItem> items = upload.parseRequest(request);
			Iterator<FileItem> iter = items.iterator();
			while (iter.hasNext()) {
			    FileItem item = iter.next();
			    if (!item.isFormField()) {
			       System.out.println("查找到一个二进制数据");
			       System.out.println("该文件表单name为："+item.getFieldName());
			       System.out.println("该文件文件名为："+item.getName());
			       System.out.println("该文件文件类型为："+item.getContentType());
			       System.out.println("该文件文件大小为："+item.getSize());
			       System.out.println();
			       String path=this.getServletContext().getRealPath("file");
			       File pathFile=new File(path);
			       if(!pathFile.exists()){
			    	   pathFile.mkdirs();
			       }
			       String sourceFileAbsolutePath=item.getName();
			       String sourceFileName=sourceFileAbsolutePath.substring(sourceFileAbsolutePath.lastIndexOf('\\')+1);
			       File uploadedFile = new File(this.getServletContext().getRealPath("file")+"\\"+sourceFileName);
			       //item.write(uploadedFile);
			       InputStream inputStream=item.getInputStream();
			       String str=ExcelUtils.readExcel(inputStream);
			       System.out.println(str);
			    }
			}
			
		}catch (Exception e) {
			e.printStackTrace();
		}
	}

}
